﻿using System;
using System.Collections.Generic;
using System.Data;

namespace com.uplus.data
{
    /// <summary>
    /// 单条数据类
    /// </summary>
    [Serializable]
    public class DmRecord
    {
        DataRow row = null;
        public DmRecord(DataTable dt)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                if (string.IsNullOrEmpty(dt.TableName)) dt.TableName = "DmRecordDT";
                row = dt.Rows[0];
            }
        }

        public DmRecord(DataRow dr)
        {
            if (dr != null)
            {
                row = dr;
            }
        }

        public int Count
        {
            get
            {
                return HasValue ? row.Table.Columns.Count : 0;
            }
        }

        public bool HasValue
        {
            get
            {
                return row != null;
            }
        }

        public Dictionary<string, object> ToDic()
        {
            Dictionary<string, object> re = new Dictionary<string, object>();
            foreach (DataColumn item in row.Table.Columns)
            {
                re.Add(item.ColumnName.ToLower(), row[item.ColumnName]);
            }
            return re;
        }

        public object this[string columnName]
        {
            get
            {
                return this.row.Table.Columns.Contains(columnName) ? this.row[columnName] : new object();
            }
            set
            {
                row[columnName] = value;
            }
        }

        public T To<T>(string column, T defaultValue)
        {
            if (this.Contains(column))
            {
                try
                {
                    object re = Convert.ChangeType(row[column], typeof(T));
                    return (T)re;
                }
                catch { }
            }
            return defaultValue;
        }

        public string ToString(string column)
        {
            return string.Format("{0}", this[column]);
        }

        public bool Contains(string column)
        {
            if (this.row != null)
                return this.row.Table.Columns.Contains(column);
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 获取本条记录对应的DataTable
        /// </summary>
        /// <returns></returns>
        public DataTable GetDT()
        {
            return this.row == null ? null : this.row.Table;
        }
    }
}
